const appSetting = require( '../setting' );
const apiKey = require( '../models/api_key' );
const uuidV4 = require( 'uuid/v4' );

exports.generateKey = () => {
    let uuid = uuidV4().replace( /-/g, '' );
    let buffer = new Buffer( uuid );
    return buffer.toString( 'base64' ).replace( /=/g, '' );
}

exports.generateAK = () => {
    let uuid = uuidV4().replace( /-/g, '' );
    let buffer = new Buffer( uuid );
    return buffer.toString( 'base64' ).replace( /=/g, '' );
}

function genAk() {
    var uid = uuid.v4().replace( /-/g, '' );
    var buffer = new Buffer( uid );
    return buffer.toString( 'base64' ).replace( /=/g, '' );
}

const getAutoGeneratedAk = async function( userId ) {
    var akTrustAutogenerate = appSetting.getSetting( 'ak.trust.autogenerate' );

    var result = await apiKey.getByCreateBy( userId, akTrustAutogenerate, "browser", 0 );
    if ( result.length === 0 ) {
        var apikey = {
            userId: userId,
            key: genAk(),
            trust: akTrustAutogenerate,
            type: "browser",
            description: "系统自动生成，删除将导致使用该AK的应用或内容无法访问。",
            createdBy: 0
        };
        var results =  await apiKey.insert( apikey );

        if ( results ) {
            return results[ 0 ];
        }

        return null;

    } else {
        return result[ 0 ];
    }
}

const getAk = async function( userId ) {

    var result = await apiKey.getByCreateBy( userId, '', "browser", 1 );   
    if ( result.length === 0 ) {
        var ak = await getAutoGeneratedAk( userId );
        return ak;
    } else {
        return result[ 0 ];
    }
}


exports.getAutoGeneratedAk = getAutoGeneratedAk;
exports.getAk = getAk;
